package com.huidu.bitrade.controller;

import cn.hutool.core.bean.BeanUtil;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.huidu.bitrade.constant.SysConstant;
import com.huidu.bitrade.constant.SystemConfigConstants;
import com.huidu.bitrade.entity.ActivityHdzOrder;
import com.huidu.bitrade.entity.ActivityHdzOrderDetail;
import com.huidu.bitrade.entity.ActivityOrder;
import com.huidu.bitrade.entity.MemberWallet;
import com.huidu.bitrade.entity.transform.AuthMember;
import com.huidu.bitrade.pagination.PageResult;
import com.huidu.bitrade.query.HdzOrderDetailQuery;
import com.huidu.bitrade.result.page.PageCondition;
import com.huidu.bitrade.service.ActivityHdzOrderDetailService;
import com.huidu.bitrade.service.ActivityHdzOrderService;
import com.huidu.bitrade.service.MemberWalletService;
import com.huidu.bitrade.util.BigDecimalUtils;
import com.huidu.bitrade.util.MessageResult;
import com.huidu.bitrade.vo.ActivityHdzOrderInfoVo;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiModelProperty;
import io.swagger.annotations.ApiOperation;
import lombok.Data;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.collections4.CollectionUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.client.RestTemplate;

import java.math.BigDecimal;
import java.math.RoundingMode;
import java.time.Duration;
import java.time.Instant;
import java.time.LocalDateTime;
import java.time.ZoneId;
import java.time.format.DateTimeFormatter;
import java.time.temporal.ChronoUnit;
import java.util.List;
import java.util.Objects;
import java.util.stream.Collectors;

@Slf4j
@RestController
@RequestMapping("activityHdz")
@RequiredArgsConstructor
@Api(tags = "hdz矿机投资")
public class ActivityHdzOrderController {

    private final ActivityHdzOrderService activityHdzOrderService;
    private final ActivityHdzOrderDetailService activityHdzOrderDetailService;
    @ApiOperation("查询矿机投资记录")
    @GetMapping("getHdzOrderRecord")
    public MessageResult<List<ActivityHdzOrder>> getHdzOrderRecord(@SessionAttribute(SysConstant.SESSION_MEMBER) AuthMember member) {
        List<ActivityHdzOrder> list = activityHdzOrderService.list(Wrappers.<ActivityHdzOrder>lambdaQuery()
                .eq(ActivityHdzOrder::getMemberId,member.getId())
                .orderByDesc(ActivityHdzOrder::getCreateTime));
        return MessageResult.success("查询成功",list);
    }

    @ApiOperation("查询用户申购总量")
    @GetMapping("getActivityCount")
    public MessageResult<BigDecimal> getActivityCount(@SessionAttribute(SysConstant.SESSION_MEMBER) AuthMember member) {
        List<ActivityHdzOrder> list = activityHdzOrderService.list(Wrappers.<ActivityHdzOrder>lambdaQuery().eq(ActivityHdzOrder::getMemberId,member.getId()));
        BigDecimal amount = BigDecimal.ZERO;
        if(CollectionUtils.isNotEmpty(list)){
            for(ActivityHdzOrder order :list){
                amount = amount.add(order.getNumber());
            }
        }
        return MessageResult.success("查询成功",amount.setScale(2, RoundingMode.DOWN));
    }

    @ApiOperation("查询矿机详情")
    @GetMapping("getHdzOrderInfo/{id}")
    public MessageResult<ActivityHdzOrderInfoVo> getHdzOrderInfo(@PathVariable Long id) {
        ActivityHdzOrder activityHdzOrder = activityHdzOrderService.getById(id);
        log.info(activityHdzOrder.toString());
        ActivityHdzOrderInfoVo activityHdzOrderInfoVo = new ActivityHdzOrderInfoVo();
        BeanUtil.copyProperties(activityHdzOrder,activityHdzOrderInfoVo);
        //时间戳转时间
        Instant instant = Instant.ofEpochMilli(activityHdzOrder.getCreateTime()); // 将时间戳转换为Instant对象
        LocalDateTime dateTime = LocalDateTime.ofInstant(instant, ZoneId.systemDefault()); // 将Instant对象转换为LocalDateTime对象
        DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd"); // 指定日期格式
        activityHdzOrderInfoVo.setCreateTime(dateTime.format(formatter));
        activityHdzOrderInfoVo.setInterestTime(dateTime.plusDays(1).format(formatter));
        long days = Duration.between(dateTime, LocalDateTime.now()).toDays();
        if(Objects.nonNull(activityHdzOrder.getRedeemTime())){
            LocalDateTime endTime = LocalDateTime.ofInstant(Instant.ofEpochMilli(activityHdzOrder.getRedeemTime()), ZoneId.systemDefault()); // 将Instant对象转换为LocalDateTime对象
            days = Duration.between(dateTime, endTime).toDays();
        }
        activityHdzOrderInfoVo.setDays(days);
        //获取赎回率,传入时间参数，返回赎回率
        activityHdzOrderInfoVo.setRedeemRate(activityHdzOrderService.getConfigRedeem(activityHdzOrder.getCreateTime()));
        //赎回扣除
        BigDecimal deduct = activityHdzOrderInfoVo.getRedeemRate().multiply(activityHdzOrder.getNumber()).divide(BigDecimal.valueOf(100),8,RoundingMode.DOWN);
        activityHdzOrderInfoVo.setDeduct(deduct);
        activityHdzOrderInfoVo.setEarnings(activityHdzOrder.getNumber().subtract(deduct).setScale(8,RoundingMode.DOWN));
        //获取参与时间
        LocalDateTime time = LocalDateTime.ofInstant(Instant.ofEpochMilli(activityHdzOrder.getCreateTime()), ZoneId.systemDefault()); // 将Instant对象转换为LocalDateTime对象
        long years = time.until(LocalDateTime.now(), ChronoUnit.YEARS);
        switch ((int) years){
            case 0:
                activityHdzOrderInfoVo.setMessage("注意：因您挖矿时长<1年，将扣除赎回费：本金 * "+activityHdzOrderInfoVo.getRedeemRate()+"%");
                break;
            case 1:
                activityHdzOrderInfoVo.setMessage("注意：因您1年<挖矿时长<2年，将扣除赎回费：本金 * "+activityHdzOrderInfoVo.getRedeemRate()+"%");
                break;
            case 2:
                activityHdzOrderInfoVo.setMessage("注意：因您2年<挖矿时长<3年，将扣除赎回费：本金 * "+activityHdzOrderInfoVo.getRedeemRate()+"%");
                break;
            case 3:
                activityHdzOrderInfoVo.setMessage("注意：因您挖矿时长>=3年，不扣除赎回费");
                break;
        }
        return MessageResult.success("",activityHdzOrderInfoVo);
    }

    @ApiOperation("查询收益明细")
    @GetMapping("getHdzOrderDetail")
    public MessageResult<PageResult<ActivityHdzOrderDetail>> getHdzOrderDetail(@SessionAttribute(SysConstant.SESSION_MEMBER) AuthMember member,HdzOrderDetailQuery detailQuery) {
        detailQuery.setMemberId(member.getId());
        return MessageResult.success("查询成功",new PageResult<>(activityHdzOrderDetailService.pageList(PageCondition.page(detailQuery),detailQuery)));
    }

    @ApiOperation("立即赎回")
    @PostMapping("redeem/{id}")
    public MessageResult redeem(@PathVariable Long id) {
        ActivityHdzOrder activityHdzOrder = activityHdzOrderService.getById(id);
        if(activityHdzOrder.getStatus()==2){
            return MessageResult.error("当前订单状态不可赎回");
        }
        activityHdzOrderService.redeemOrder(id);
        return MessageResult.success();
    }

    @ApiOperation("参与质押活动")
    @RequestMapping("pledge")
    public MessageResult pledge(Long memberId,BigDecimal amount,Long activityId) {
        return activityHdzOrderService.pledge(memberId,amount,activityId);
    }

}
